package com.tarena.lbs.basic.web.dao.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.basic.web.dao.mapper.BusinessMapper;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.query.BusinessQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class BusinessRepository extends ServiceImpl<BusinessMapper, BusinessPO> {
    @Autowired
    private BusinessMapper businessMapper;

    public List<BusinessPO> getPageList(Integer from, Integer pageSize){
        //select * from lbs_businss limit from,size;
        return businessMapper.getPageList(from, pageSize);
    }

    public PageInfo<BusinessPO> businessPage(BusinessQuery query){
        //根据业务条件封装查询QueryWrapper
        QueryWrapper<BusinessPO> queryWrapper = assemBelQuery(query);
        Integer pageSize = query.getPageSize();
        Integer pageNo = query.getPageNo();
        //1.使用pageHelper开启一个分页执行
        PageHelper.startPage(pageNo,pageSize);
        //2.直接使用持久层 查询与业务条件queryWrapper有关的商家列表
        List<BusinessPO> pos = businessMapper.selectList(queryWrapper);
        log.info("当前列表查询的pos实际的返回值类型:{}",pos.getClass().getName());
        //3.将列表查询结果 包装到一个PageInfo对象里 触发封装分页的条件
        PageInfo<BusinessPO> pageInfo = new PageInfo<>(pos);
        //pageHelper到此为止 已经默默封装了所有分页的数据 pageNo pageSize total list
        log.info("当前页:{}",pageInfo.getPageNum());//pageNo
        log.info("每页条:{}",pageInfo.getPageSize());//pageSize
        log.info("总页数:{}",pageInfo.getTotal());//total
        log.info("分页数据:{}",pageInfo.getList());//object
        return pageInfo;
    }

    private QueryWrapper<BusinessPO> assemBelQuery(BusinessQuery query) {
        //利用非空业务字段 封装查询条件
        QueryWrapper<BusinessPO> queryWrapper = new QueryWrapper<>();
        if (query.getBusinessName()!=null){
            queryWrapper.like("business_name",query.getBusinessName());
        }
        if(query.getBusinessHeadPhone()!=null){
            queryWrapper.eq("business_head_phone",query.getBusinessHeadPhone());
        }
        if(query.getBusinessStatus()!=null){
            queryWrapper.eq("business_status",query.getBusinessStatus());
        }
        if(query.getStartingTime()!=null){
            queryWrapper.ge("entry_time",query.getStartingTime());
        }
        if(query.getEndTime()!=null){
            queryWrapper.le("entry_time",query.getEndTime());
        }
        if (query.getBusinessId()!=null) {
            queryWrapper.eq("id",query.getBusinessId());
        }
        return queryWrapper;
    }

    public BusinessPO getBusiness(Integer businessId) {
        return businessMapper.selectById(businessId);
    }
}
